package lazy.tool;

import java.io.*;

/**
 * 用來同步兩個資料夾內容。<br />
 * 比對兩個資料夾檔案有無更動，若有更動則從同步的對象複製檔案至被同步的對象。<br />
 * 比對依據檔案大小及最後編輯時間。以下是範例程式：<br />
 * <pre>
 * FileSyncer f = new FileSyncer();
 * //sync(被同步的資料夾, 同步對象的資料夾)
 * f.sync(new File("c:/main"), new File("c:/target"));
 * </pre>
 * 另外也提供一個刪除整個資料夾的小功能：<br />
 * <pre>
 * f.deleteFolder(new File("c:/main"));
 * </pre>
 * @author Administrator
 */
public class FileSyncer {
	private byte[] buffer = new byte[10*1024];
	public void copy(File from, File to) {
		FileInputStream in = null;
		FileOutputStream out = null;
		try {
			in = new FileInputStream(from);
			out = new FileOutputStream(to);
			int len = -1;
			while((len=in.read(buffer))!=-1) {
				out.write(buffer, 0, len);
			}
			System.out.print("Copy from:");
			System.out.print(from);
			System.out.print(", to:");
			System.out.println(to);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(in!=null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(out!=null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			to.setLastModified(from.lastModified());
		}
	}
	public void sync(File mainFolder, File targetFolder) {
		if(mainFolder==null || targetFolder==null
		|| !mainFolder.exists() || !targetFolder.exists()
		|| !mainFolder.isDirectory() || !targetFolder.isDirectory())
			throw new NotFolderException();
		//---------------------------------------
		File[] targetFiles = targetFolder.listFiles();
		if(targetFiles!=null && targetFiles.length>0) {
			File mainFile = null;
			StringBuilder sb = new StringBuilder();
			for(File f:targetFiles) {
				sb.delete(0, sb.length());
				mainFile = new File(sb.append(mainFolder.getAbsolutePath()).append("/").append(f.getName()).toString());
				if(mainFile.exists()) {	//存在
					if(f.isFile()) {	//檔案
						if(f.lastModified()!=mainFile.lastModified() || f.length()!=mainFile.length()) copy(f, mainFile);
					} else {	//路徑
						sync(mainFile, f);
					}
				} else {	//不存在
					if(f.isFile()) {	//檔案
						copy(f, mainFile);
					} else {	//路徑
						if(mainFile.mkdir()) sync(mainFile, f);
					}
				}
			}
		}
	}
	private void delete(int index, File file) {
		if(file!=null) {
			System.out.print("Index:");
			System.out.print(index);
			System.out.print(". Delete:");
			System.out.print(file.delete());
			System.out.print(". Path:");
			System.out.println(file);
		}
	}
	private void deleteFolder(File file, int index) {
		if(file.isFile()) {
			delete(index, file);
		} else {
			File[] fs = file.listFiles();
			if(fs!=null && fs.length>0) {
				for(File f:fs) {
					deleteFolder(f, index+1);
				}
			}
			delete(index, file);
		}
	}
	public void deleteFolder(File file) {
		deleteFolder(file, 0);
	}
}
